package com.china08.yxyapi.api.comm.bigfileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyLessonsTempRepository;
import com.china08.yxyapi.util.YxyResUtil;

@CrossOrigin
@RestController
public class BigFileBlockMergeNewController extends YxyApiBaseController {

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @Autowired
    YxyLessonsTempRepository tempRepository;

    @RequestMapping(value = "/api_yw/comm/bigfile/upload/block/merge", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(@RequestBody ReqModel model) throws Exception {
        RespModel respModel = new RespModel();

        long l1 = System.currentTimeMillis();

        String md5 = model.md5;
        String ext = model.extension;

        // 年月日+md5前2个字符串
        String path0 = YxyResUtil.getPath() + File.separator + md5.substring(0, 2);
        // 临时目录，为转码视频目录
        String path1 = uploadBasePath + "/temp" + YxyResUtil.getPathMonth() + File.separator + md5;
        // 保存新上传文件路径
        String path2 = uploadBasePath + path0;
        // 保存新上传文件完整路径
        String path3 = path2 + File.separator + md5 + "." + ext;
        // 保存数据库完整路径
        String location = path0 + File.separator + md5 + "." + ext;

        /**
         * 判断为合并视频临时目录是否存在
         */
        File file1 = new File(path1);
        if (!file1.exists() || !file1.isDirectory()) {
            respModel.success = false;
            respModel.location = "";
            return respModel;
        }

        /**
         * 判断合并视频目录是否存在 不存在：创建目录
         */
        try {
            File file2 = new File(path2);
            if (!file2.exists()) {
                FileUtils.forceMkdir(file2);
            }
        } catch (Exception e) {
            respModel.success = false;
            respModel.location = "";
            System.out.println("创建合并视频目录失败");
            e.printStackTrace();
            return respModel;
        }

        /**
         * 判断合并视频是否存在 视频已经存在返回视频的路径 不存在合并视频
         */
        File file3 = new File(path3);
        if (file3.exists()) {
            System.out.println("视频已经存在,无需合并");
            respModel.success = true;
            respModel.location = location;
        } else {
            // 临时目录中的文件集合，未合并视频片段
            String[] tempFilelist = file1.list();

            // 未合并视频片段个数
            Integer tempFileLenght = tempFilelist.length;

            // 创建视频写入
            OutputStream writer = null;
            try {
                // 创建视频写入
                writer = new FileOutputStream(path3);
                // 创建读取流
                InputStream reader = null;
                int len;
                byte[] cbuf = new byte[1024 * 1024];
                for (int i = 0; i < tempFileLenght; i++) {
                    reader = new FileInputStream(path1 + File.separator + i);
                    while ((len = reader.read(cbuf, 0, cbuf.length)) != -1) {
                        writer.write(cbuf, 0, len);
                        writer.flush();
                    }
                    reader.close();
                }
                writer.close();
                respModel.success = true;
                respModel.location = location;
            } catch (Exception e) {
                writer.close();
                e.printStackTrace();
                respModel.success = false;
                respModel.location = "";
            }
        }

        try {
            // Thread.sleep(20000);
        } catch (Exception e) {
        }
        System.out.println("合并用时：" + (System.currentTimeMillis() - l1));
        return respModel;
    }

    protected static class RespModel extends YxyApiRespModel {
        public boolean success = true;
        public String location;
    }

    protected static class ReqModel extends YxyApiReqModel {
        public String md5;// 整个文件的md5
        public String extension; // 文件后缀

        @Override
        public void autoCheck() {
            Assert.isTrue(StringUtils.isNotBlank(md5), "视频md5不能为空");
            Assert.isTrue(StringUtils.isNotBlank(extension), "视频后缀不能为空");
        }
    }
}
